<?php
/*
 *                        _oo0oo_
 *                       o8888888o
 *                       88" . "88
 *                       (| -_- |)
 *                       0\  =  /0
 *                     ___/`---'\___
 *                   .' \\|     |// '.
 *                  / \\|||  :  |||// \
 *                 / _||||| -:- |||||- \
 *                |   | \\\  - /// |   |
 *                | \_|  ''\---/''  |_/ |
 *                \  .-\__  '-'  ___/-. /
 *              ___'. .'  /--.--\  `. .'___
 *           ."" '<  `.___\_<|>_/___.' >' "".
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /
 *      =====`-.____`.___ \_____/___.-`___.-'=====
 *                        `=---='
 * 
 * 
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 
 *            佛祖保佑       永不宕机     永无BUG
 */
/*
 * 用户操作页
 * @Author: htong
 * @Date: 2021-03-02 18:16:55
 * @LastEditors: htong
 * @LastEditTime: 2021-03-02 18:39:06
 * @Description: file content
 * @FilePath: \gongchengqiaojob\Application\Home\Controller\PcUserapiController.class.php
 */
namespace Home\Controller;
use Common\Controller\PcApiController;
use Common\ORG\PublicFunction;
use Common\ORG\WxFunction;
use Think\Db;

class PcUserapiController extends PcApiController{
	private $category   = [
        1 => 'reg_',    //用户注册 用户短信或邮件
        2 => 'login_',  //用户登陆 用户短信或邮件
        3 => 'mpw_',    //修改密码 用户短信或邮件
        4 => 'pcuid_',    //token注册缓存
        5 => 'mtel_',    //修改手机号
        6 => 'mwithdraw_',    //提现验证
        7 => 'mgcb_',    //工程币支付验证
        8 => 'share_',   //分享验证
    ];  //缓存类型
	public function _initialize() {
        
        $getsecret  = $_SERVER['HTTP_APPSECRET'];
        //取head标签内容
        if(!preg_match('/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/', $getsecret) && ACTION_NAME<>'getUserInfo'){
            $this->ajaxReturn(1, 'appsecret格式错误');
        }

        if($this->appsecret <> $getsecret && ACTION_NAME<>'getUserInfo'){
            $this->ajaxReturn(1, 'appsecret错误');
        }
        parent::_initialize();
    }

	/**
	 * @name: 登录
	 * @description: 
	 * @Author: htong
	 * @msg: 
	 * @param int       $loginype (必填：是) 登陆类型 1、微信登陆 2、短信登陆 3、密码登陆
	 * @param string    $mobile (必填：是) 用户账号 可能是用户名、手机号、邮箱
	 * @param string    $password (选填：是) 用户密码
	 * @param int       $mobileVcode (选填：否) 手机验证码
	 * @param int       $userinfo (选填：否) 微信登陆用户信息
	 * @return json
	 */	
	public function Signin(){
		
		if(!IS_POST){
            $this->ajaxReturn(1, '提交方式错误！');
        }
        $loginType      = I('post.login_type', 0, 'intval');
        $mobile         = I('post.mobile', '', 'trim');  //用户账号
        $password       = I('post.password', '', 'trim');   //密码
        $mobileVcode    = I('post.mobile_vcode', 0, 'intval'); //手机验证码
        $userinfo       = I('post.userinfo');//微信登陆用户信息
        $sms            = S($this->category[2].$mobile); //登陆短信验证码
        $sms            = 123456;
        $mobile_mod     = D('Members');
        if(!in_array($loginType, [1,2,3])){
            $this->ajaxReturn(1,'登陆类型错误');
        }
        if($loginType==1) {
            //微信登陆

            $wxInfo = wxUserInfo($userinfo);
            if($wxInfo['status']==1) $this->ajaxReturn(1, $wxInfo['msg']);

            $mb = M('MembersBind')->where(['openid'=>$wxInfo['data']['wxdata']['openId']])->find();
            if(!$mb){
                $this->ajaxReturn(6, '微信绑定信息不存在', $wxInfo['data']);//用户不存在
            }
            $check_map['uid'] = array('eq',$mb['uid']);
        } elseif($loginType==2) {
            //短信登陆

            if(empty($mobile) || empty($mobileVcode)){
                $this->ajaxReturn(1, '登陆信息错误');
            }

            if (!fieldRegex($mobile,'mobile')) {
                $this->ajaxReturn(1, '手机格式错误');
            }

            if(!$sms){
                $this->ajaxReturn(1, '验证码不存在或已过期');
            }

            if($sms <> $mobileVcode){
                $this->ajaxReturn(1, '手机验证码错误');
            }
            S($this->category[2].$mobile, '');
            $check_map['mobile'] = array('eq',$mobile);
        }else{
            //密码登陆

            if(empty($mobile) || empty($password)){
                $this->ajaxReturn(1, '登陆信息错误');
            }
            $account_type='username';
            if (fieldRegex($mobile,'email'))
            {
                $account_type='email';
            }elseif (fieldRegex($mobile,'mobile')) {
                $account_type='mobile';
            }
            $check_map[$account_type] = array('eq',$mobile);
        }
		$check_map['utype'] = array('eq',1);
        if(!$user = $mobile_mod->where($check_map)->find()) {
            $this->ajaxReturn(1, L('auth_null'));//用户不存在
        }

        if(!in_array($loginType,array(1, 2)) || !empty($password)) {
            $pwd = $mobile_mod->make_md5_pwd($password, $user['pwd_hash']);
            if ($pwd <> $user['password']) {
                $this->ajaxReturn(1, L('auth_password_failed'));//密码错误
            }
        }

        if($user['status'] == 2){
            $this->ajaxReturn(1, L('account_disabled'));//停用
        }elseif($user['status'] == 0){
            $this->ajaxReturn(1, L('auth_activation'));//未激活
        }

        //登陆日志
        write_members_log($user,'login','用户登录','PC');

        $newUser    = [
                "uid"       => $user['uid'],
                "utype"     => intval($user['utype']),
                "username"  => $user['username'],
                "email"     => $user['email'],
                "mobile"    => $user['mobile'],
                "reg_time"  => date('Y-m-d H:i:s', $user['reg_time']),
                "last_login_time"   => date('Y-m-d H:i:s', $user['reg_time']),
                "status"    => intval($user['status']), //0未激活 1正常 2 停用
                "avatars"   => !empty($user['avatars']) ? attach($user['avatars'], 'avatar') : attach('default.png', 'avatar'),
                'token'     => $result = $this->generateToken($user['uid']),
        ];

        $this->ajaxReturn(0, 'ok', $newUser);
	}

    

	//生成token
    private function generateToken($uid){

        $randStr    = PublicFunction::createNoncestr(6);//随机字符串
        $data       = array(
            'uid'       => $uid,
            'appkey'    => $this->appkey,
            'appsecret' => $this->appsecret,
            'randStr'   => $randStr
        );
        $options    = 0;//数据格式选项（可选）
        $iv         = '';//加密初始化向量（可选）
        $result = openssl_encrypt(json_encode($data), 'AES-128-CBC', $this->appsecret, $options, $iv); //AES-128-CBC加密方式
        S($this->category[4].$uid,$result,7200);
        
        return $result;
    }


    public function gettoken(){

        //$appid      = M('Members')->query('select uuid_short() as token'); //mysql计算用户UUID
        $uid        = I('post.uid', 0,'intval');
        if(empty($uid)){
            $this->ajaxReturn(1,'用户ID不能为空！');
        }

        $userinfo   = M('members')->where(['uid'=>$uid])->find();
        //echo M('members')->getLastSql();exit;
        if(empty($userinfo)){
            $this->ajaxReturn(1, '用户信息不存在！');
        }

        $result = $this->generateToken($uid);
        $this->ajaxReturn(0, 'ok', ['token'=>$result]);
    }

}
?>